<template>
  <div class="p-6 customers-page bg-gray-50 dark:bg-gray-900 min-h-screen">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h2 class="text-2xl font-bold dark:text-white">客户管理</h2>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
      <a-card class="stat-card dark:bg-gray-800" :bordered="false">
        <div class="stat-content">
          <div class="stat-title dark:text-gray-300">总客户数</div>
          <div class="stat-value dark:text-white">2,458</div>
          <div class="stat-compare dark:text-gray-400">
            <span class="trend-up dark:text-green-400">
              <icon-arrow-rise /> +12.5%
            </span>
            较上月
          </div>
        </div>
      </a-card>
      <a-card class="stat-card dark:bg-gray-800" :bordered="false">
        <div class="stat-content">
          <div class="stat-title dark:text-gray-300">本月新增</div>
          <div class="stat-value dark:text-white">186</div>
          <div class="stat-compare dark:text-gray-400">
            <span class="trend-up dark:text-green-400">
              <icon-arrow-rise /> +8.3%
            </span>
            较上月
          </div>
        </div>
      </a-card>
      <a-card class="stat-card dark:bg-gray-800" :bordered="false">
        <div class="stat-content">
          <div class="stat-title dark:text-gray-300">客户活跃度</div>
          <div class="stat-value dark:text-white">85%</div>
          <div class="stat-compare dark:text-gray-400">
            <span class="trend-up dark:text-green-400">
              <icon-arrow-rise /> +5.2%
            </span>
            较上月
          </div>
        </div>
      </a-card>
      <a-card class="stat-card dark:bg-gray-800" :bordered="false">
        <div class="stat-content">
          <div class="stat-title dark:text-gray-300">平均消费</div>
          <div class="stat-value dark:text-white">¥1,280</div>
          <div class="stat-compare dark:text-gray-400">
            <span class="trend-up dark:text-green-400">
              <icon-arrow-rise /> +15.8%
            </span>
            较上月
          </div>
        </div>
      </a-card>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white dark:bg-gray-800 rounded-lg p-6 mb-6">
      <a-form
        :model="searchForm"
        layout="inline"
        class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4"
      >
        <a-form-item
          field="keyword"
          label="关键词搜索"
          class="w-full dark:text-gray-300"
        >
          <a-input-search
            v-model="searchForm.keyword"
            placeholder="姓名/手机号/身份证号"
            search-button
            @search="handleSearch"
            class="dark:bg-gray-700 dark:text-gray-300"
          />
        </a-form-item>
        <a-form-item
          field="memberLevel"
          label="会员等级"
          class="w-full dark:text-gray-300"
        >
          <a-select
            v-model="searchForm.memberLevel"
            placeholder="请选择会员等级"
            allow-clear
            class="dark:bg-gray-700 dark:text-gray-300"
          >
            <a-option value="normal">普通会员</a-option>
            <a-option value="silver">白银会员</a-option>
            <a-option value="gold">黄金会员</a-option>
            <a-option value="platinum">铂金会员</a-option>
            <a-option value="diamond">钻石会员</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="stayCount" label="入住次数" class="w-full">
          <a-select
            v-model="searchForm.stayCount"
            placeholder="请选择入住次数"
            allow-clear
          >
            <a-option value="0-5">0-5次</a-option>
            <a-option value="6-10">6-10次</a-option>
            <a-option value="11-20">11-20次</a-option>
            <a-option value=">20">20次以上</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="lastStayDate" label="最近入住" class="w-full">
          <a-range-picker
            v-model="searchForm.lastStayDate"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>

      <div class="flex justify-between items-center mt-4">
        <a-button
          type="text"
          @click="showAdvancedSearch = !showAdvancedSearch"
          class="dark:text-gray-300"
        >
          {{ showAdvancedSearch ? "收起" : "展开" }}高级筛选
          <icon-down v-if="!showAdvancedSearch" />
          <icon-up v-else />
        </a-button>
        <div class="flex space-x-4">
          <a-button type="primary" @click="showEditModal = true">
            <template #icon><icon-plus /></template>
            添加客户
          </a-button>
          <a-button @click="exportCustomerData">
            <template #icon><icon-download /></template>
            导出数据
          </a-button>
          <a-button @click="handleRefresh">
            <template #icon><icon-refresh /></template>
            刷新
          </a-button>
        </div>
      </div>

      <!-- 高级搜索 -->
      <div
        v-show="showAdvancedSearch"
        class="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700"
      >
        <a-form
          :model="searchForm"
          layout="inline"
          class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"
        >
          <a-form-item field="tags" label="客户标签" class="w-full">
            <a-select
              v-model="searchForm.tags"
              placeholder="请选择标签"
              allow-clear
              multiple
            >
              <a-option value="vip">VIP客户</a-option>
              <a-option value="frequent">常客</a-option>
              <a-option value="business">商务客户</a-option>
              <a-option value="group">团队客户</a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="source" label="客户来源" class="w-full">
            <a-select
              v-model="searchForm.source"
              placeholder="请选择来源"
              allow-clear
            >
              <a-option value="direct">直接预订</a-option>
              <a-option value="ota">OTA平台</a-option>
              <a-option value="referral">客户推荐</a-option>
              <a-option value="other">其他渠道</a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="consumption" label="消费金额" class="w-full">
            <a-input-number-range
              v-model="searchForm.consumption"
              placeholder="最小值"
              placeholder-2="最大值"
            />
          </a-form-item>
        </a-form>
      </div>
    </div>

    <!-- 客户列表 -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
      <a-table
        :data="customers"
        :columns="columns"
        :pagination="pagination"
        class="dark:bg-gray-800"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        @sorter-change="handleSorterChange"
      >
        <!-- 客户信息列 -->
        <template #info="{ record }">
          <div class="flex items-center">
            <a-avatar :size="40" :src="record.avatar" />
            <div class="ml-3">
              <div class="font-medium dark:text-white">{{ record.name }}</div>
              <div class="text-gray-500 dark:text-gray-400 text-sm">
                {{ record.phone }}
              </div>
              <div class="flex mt-1 space-x-2">
                <a-tag v-for="tag in record.tags" :key="tag" size="small">
                  {{ tag }}
                </a-tag>
              </div>
            </div>
          </div>
        </template>

        <!-- 会员等级列 -->
        <template #memberLevel="{ record }">
          <div class="flex items-center">
            <div
              class="w-2 h-2 rounded-full"
              :class="getMemberLevelColor(record.memberLevel)"
            ></div>
            <span class="ml-2 dark:text-gray-300">{{
              getMemberLevelText(record.memberLevel)
            }}</span>
            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
              积分: {{ record.points }}
            </div>
          </div>
        </template>

        <!-- 消费统计列 -->
        <template #consumption="{ record }">
          <div>
            <div class="text-lg font-medium dark:text-white">
              ¥{{ record.totalConsumption }}
            </div>
            <div class="text-gray-500 dark:text-gray-400 text-sm">
              {{ record.stayCount }}次入住
            </div>
            <a-progress
              :percent="(record.stayCount / 20) * 100"
              :show-text="false"
              size="small"
              :stroke-width="4"
            />
          </div>
        </template>

        <!-- 最近入住列 -->
        <template #lastStay="{ record }">
          <div>
            <div class="dark:text-gray-300">{{ record.lastStayDate }}</div>
            <div class="text-gray-500 dark:text-gray-400 text-sm">
              {{ record.lastRoomType }}
            </div>
          </div>
        </template>

        <!-- 操作列 -->
        <template #operation="{ record }">
          <a-space>
            <a-button
              type="text"
              size="small"
              class="dark:text-blue-400"
              @click="viewCustomerDetails(record)"
            >
              详情
            </a-button>
            <a-button
              type="text"
              size="small"
              class="dark:text-blue-400"
              @click="editCustomer(record)"
            >
              编辑
            </a-button>
            <a-dropdown>
              <a-button type="text" size="small" class="dark:text-gray-300">
                更多
                <icon-down />
              </a-button>
              <template #content>
                <a-doption @click="addNote(record)" class="dark:text-gray-300">
                  <template #icon><icon-edit /></template>
                  添加备注
                </a-doption>
                <a-doption
                  @click="sendMessage(record)"
                  class="dark:text-gray-300"
                >
                  <template #icon><icon-message /></template>
                  发送消息
                </a-doption>
                <a-doption
                  @click="addToBlacklist(record)"
                  class="dark:text-gray-300"
                >
                  <template #icon><icon-forbidden /></template>
                  加入黑名单
                </a-doption>
              </template>
            </a-dropdown>
          </a-space>
        </template>
      </a-table>
    </div>

    <!-- 客户详情弹窗 -->
    <a-modal
      v-model:visible="showDetailsModal"
      title="客户详情"
      @cancel="closeCustomerDetails"
      :footer="false"
      width="800px"
      class="customer-details-modal"
    >
      <div v-if="selectedCustomer" class="modal-content">
        <!-- 基本信息 -->
        <div>
          <h3 class="text-lg font-medium mb-4">基本信息</h3>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >姓名</label
              >
              <div class="mt-1">{{ selectedCustomer.name }}</div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >手机号</label
              >
              <div class="mt-1">{{ selectedCustomer.phone }}</div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >身份证号</label
              >
              <div class="mt-1">{{ selectedCustomer.idCard }}</div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >会员等级</label
              >
              <div class="mt-1">
                <a-tag
                  :color="getMemberLevelColor(selectedCustomer.memberLevel)"
                >
                  {{ getMemberLevelText(selectedCustomer.memberLevel) }}
                </a-tag>
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >注册时间</label
              >
              <div class="mt-1">{{ selectedCustomer.registerTime }}</div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >最近入住</label
              >
              <div class="mt-1">{{ selectedCustomer.lastStayDate }}</div>
            </div>
          </div>
        </div>

        <!-- 消费统计 -->
        <div class="border-t pt-6">
          <h3 class="text-lg font-medium mb-4">消费统计</h3>
          <div class="grid grid-cols-3 gap-4">
            <div class="bg-blue-50 rounded-lg p-4">
              <div class="text-sm text-gray-500">总消费</div>
              <div class="text-xl font-medium text-blue-600 mt-1">
                ¥{{ selectedCustomer.totalConsumption }}
              </div>
            </div>
            <div class="bg-green-50 rounded-lg p-4">
              <div class="text-sm text-gray-500">入住次数</div>
              <div class="text-xl font-medium text-green-600 mt-1">
                {{ selectedCustomer.stayCount }}次
              </div>
            </div>
            <div class="bg-purple-50 rounded-lg p-4">
              <div class="text-sm text-gray-500">积分余额</div>
              <div class="text-xl font-medium text-purple-600 mt-1">
                {{ selectedCustomer.points }}
              </div>
            </div>
          </div>
        </div>

        <!-- 入住记录 -->
        <div class="border-t pt-6">
          <h3 class="text-lg font-medium mb-4">入住记录</h3>
          <a-table
            :data="selectedCustomer.stayHistory"
            :pagination="false"
            :scroll="{ y: 240 }"
          >
            <template #columns>
              <a-table-column title="入住时间" data-index="checkInDate" />
              <a-table-column title="退房时间" data-index="checkOutDate" />
              <a-table-column title="房型" data-index="roomType" />
              <a-table-column title="房号" data-index="roomNumber" />
              <a-table-column title="消费金额" data-index="amount">
                <template #cell="{ record }"> ¥{{ record.amount }} </template>
              </a-table-column>
            </template>
          </a-table>
        </div>

        <!-- 评价记录 -->
        <div class="border-t pt-6">
          <h3 class="text-lg font-medium mb-4">评价记录</h3>
          <div class="space-y-4">
            <div
              v-for="review in selectedCustomer.reviews"
              :key="review.id"
              class="bg-gray-50 rounded-lg p-4"
            >
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <a-rate :model-value="review.rating" readonly />
                  <span class="ml-2 text-gray-500">{{ review.date }}</span>
                </div>
                <a-tag>{{ review.roomType }}</a-tag>
              </div>
              <div class="mt-2">{{ review.content }}</div>
            </div>
          </div>
        </div>

        <!-- 备注记录 -->
        <div class="border-t pt-6">
          <h3 class="text-lg font-medium mb-4">备注记录</h3>
          <div class="space-y-4">
            <div
              v-for="note in selectedCustomer.notes"
              :key="note.id"
              class="bg-gray-50 rounded-lg p-4"
            >
              <div class="flex items-center justify-between">
                <span class="text-gray-500">{{ note.date }}</span>
                <span class="text-gray-500">{{ note.operator }}</span>
              </div>
              <div class="mt-2">{{ note.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 编辑客户弹窗 -->
    <a-modal
      v-model:visible="showEditModal"
      :title="editingCustomer ? '编辑客户' : '添加客户'"
      @cancel="cancelEdit"
      @before-ok="handleSubmit"
    >
      <a-form ref="customerForm" :model="customerForm" layout="vertical">
        <a-form-item field="name" label="姓名" required>
          <a-input
            v-model="customerForm.name"
            placeholder="请输入姓名"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="phone" label="手机号" required>
          <a-input
            v-model="customerForm.phone"
            placeholder="请输入手机号"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="idCard" label="身份证号" required>
          <a-input
            v-model="customerForm.idCard"
            placeholder="请输入身份证号"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="memberLevel" label="会员等级" required>
          <a-select
            v-model="customerForm.memberLevel"
            placeholder="请选择会员等级"
          >
            <a-option value="normal">普通会员</a-option>
            <a-option value="silver">白银会员</a-option>
            <a-option value="gold">黄金会员</a-option>
            <a-option value="platinum">铂金会员</a-option>
            <a-option value="diamond">钻石会员</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="tags" label="客户标签">
          <a-select
            v-model="customerForm.tags"
            placeholder="请选择标签"
            multiple
            allow-create
          >
            <a-option value="vip">VIP客户</a-option>
            <a-option value="frequent">常客</a-option>
            <a-option value="business">商务客户</a-option>
            <a-option value="group">团队客户</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="points" label="积分">
          <a-input-number
            v-model="customerForm.points"
            placeholder="请输入积分"
            :min="0"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item field="remarks" label="备注">
          <a-textarea
            v-model="customerForm.remarks"
            placeholder="请输入备注"
            :max-length="200"
            show-word-limit
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 添加备注弹窗 -->
    <a-modal
      v-model:visible="showNoteModal"
      title="添加备注"
      @cancel="cancelNote"
      @before-ok="handleNoteSubmit"
    >
      <a-form :model="noteForm">
        <a-form-item field="content" label="备注内容" required>
          <a-textarea
            v-model="noteForm.content"
            placeholder="请输入备注内容"
            :max-length="500"
            show-word-limit
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconPlus,
  IconDownload,
  IconRefresh,
  IconEdit,
  IconMessage,
  IconBlock,
  IconDelete,
  IconDown,
  IconUp,
  IconArrowRise,
  IconArrowFall,
} from "@arco-design/web-vue/es/icon";

// 搜索表单
const searchForm = reactive({
  memberLevel: "",
  stayCount: "",
  lastStayDate: [],
  keyword: "",
  tags: [],
  source: "",
  consumption: [],
});

// 客户表单
const customerForm = reactive({
  name: "",
  phone: "",
  idCard: "",
  memberLevel: "normal",
  tags: [],
  points: 0,
  remarks: "",
});

// 备注表单
const noteForm = reactive({
  content: "",
});

// 表格列配置
const columns = [
  {
    title: "客户信息",
    slotName: "info",
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
  },
  {
    title: "会员等级",
    slotName: "memberLevel",
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
  },
  {
    title: "消费统计",
    slotName: "consumption",
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
  },
  {
    title: "最近入住",
    slotName: "lastStay",
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
  },
  {
    title: "注册时间",
    dataIndex: "registerTime",
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
  },
  {
    title: "操作",
    slotName: "operation",
    width: 180,
    fixed: "right",
  },
];

// 分页配置
const pagination = reactive({
  total: 100,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 控制显示状态
const showAdvancedSearch = ref(false);
const showDetailsModal = ref(false);
const showEditModal = ref(false);
const showNoteModal = ref(false);
const selectedCustomer = ref(null);
const editingCustomer = ref(null);

// 模拟客户数据
const customers = ref([
  {
    id: 1,
    name: "张三",
    phone: "13800138000",
    idCard: "110101199001011234",
    avatar: "/avatar-1.jpg",
    memberLevel: "gold",
    totalConsumption: 12680,
    stayCount: 8,
    points: 2680,
    registerTime: "2023-12-01",
    lastStayDate: "2024-02-25",
    lastRoomType: "豪华大床房",
    tags: ["VIP客户", "常客"],
    stayHistory: [
      {
        checkInDate: "2024-02-25",
        checkOutDate: "2024-02-26",
        roomType: "豪华大床房",
        roomNumber: "801",
        amount: 688,
      },
    ],
    reviews: [
      {
        id: 1,
        rating: 5,
        content: "房间很干净，服务很好，位置也很方便。",
        date: "2024-02-26",
        roomType: "豪华大床房",
      },
    ],
    notes: [
      {
        id: 1,
        content: "客户喜欢安静的房间，建议安排高层。",
        date: "2024-02-25",
        operator: "王经理",
      },
    ],
  },
]);

// 获取会员等级颜色
const getMemberLevelColor = (level) => {
  const colors = {
    normal: "bg-gray-400",
    silver: "bg-blue-400",
    gold: "bg-yellow-400",
    platinum: "bg-purple-400",
    diamond: "bg-red-400",
  };
  return colors[level] || "bg-gray-400";
};

// 获取会员等级文本
const getMemberLevelText = (level) => {
  const texts = {
    normal: "普通会员",
    silver: "白银会员",
    gold: "黄金会员",
    platinum: "铂金会员",
    diamond: "钻石会员",
  };
  return texts[level] || level;
};

// 搜索客户
const handleSearch = () => {
  // 调用API搜索客户
};

// 刷新数据
const handleRefresh = () => {
  // 重新加载数据
};

// 导出数据
const exportCustomerData = () => {
  // 导出数据处理
};

// 查看客户详情
const viewCustomerDetails = (customer) => {
  selectedCustomer.value = customer;
  showDetailsModal.value = true;
};

// 关闭客户详情
const closeCustomerDetails = () => {
  showDetailsModal.value = false;
  selectedCustomer.value = null;
};

// 编辑客户
const editCustomer = (customer) => {
  editingCustomer.value = customer;
  Object.keys(customerForm).forEach((key) => {
    customerForm[key] = customer[key];
  });
  showEditModal.value = true;
};

// 删除客户
const deleteCustomer = async (customer) => {
  try {
    // 调用API删除客户
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("删除成功");
    // 重新加载客户列表
    handleSearch();
  } catch (error) {
    Message.error("删除失败");
  }
};

// 取消编辑
const cancelEdit = () => {
  editingCustomer.value = null;
  Object.keys(customerForm).forEach((key) => {
    customerForm[key] = "";
  });
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 调用API保存客户信息
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success(editingCustomer.value ? "修改成功" : "添加成功");
    showEditModal.value = false;
    cancelEdit();
    // 重新加载客户列表
    handleSearch();
    return true;
  } catch (error) {
    Message.error(editingCustomer.value ? "修改失败" : "添加失败");
    return false;
  }
};

// 添加备注
const addNote = (customer) => {
  selectedCustomer.value = customer;
  showNoteModal.value = true;
};

// 取消添加备注
const cancelNote = () => {
  noteForm.content = "";
  showNoteModal.value = false;
};

// 提交备注
const handleNoteSubmit = async () => {
  try {
    // 调用API保存备注
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("添加备注成功");
    showNoteModal.value = false;
    cancelNote();
    return true;
  } catch (error) {
    Message.error("添加备注失败");
    return false;
  }
};

// 发送消息
const sendMessage = (customer) => {
  Message.success(`已向${customer.name}发送消息`);
};

// 加入黑名单
const addToBlacklist = (customer) => {
  Message.success(`已将${customer.name}加入黑名单`);
};

// 分页相关方法
const onPageChange = (current) => {
  pagination.current = current;
  handleSearch();
};

const onPageSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  handleSearch();
};

// 修改排序处理函数
const handleSorterChange = (sorter) => {
  // 处理排序逻辑，移除通知提示
  handleSearch();
};
</script>

<style lang="less" scoped>
.customers-page {
  :deep(.arco-table-th) {
    background-color: var(--color-bg-2);
    &.dark {
      background-color: #1f2937;
      color: #e5e7eb;
    }
  }

  :deep(.arco-table-td) {
    &.dark {
      background-color: #1f2937;
      color: #e5e7eb;
    }
  }

  :deep(.arco-input-wrapper),
  :deep(.arco-select-view),
  :deep(.arco-picker) {
    .dark & {
      background-color: #374151;
      border-color: #4b5563;

      &:hover,
      &:focus {
        border-color: #60a5fa;
      }
    }
  }

  :deep(.arco-dropdown-menu) {
    .dark & {
      background-color: #1f2937;
      border-color: #4b5563;
    }
  }

  .stat-card {
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
    }
  }
}

// 添加模态框滚动样式
:deep(.customer-details-modal) {
  .arco-modal-body {
    max-height: 70vh;
    overflow-y: auto;
  }
}

// 添加表格样式
:deep(.arco-table-th) {
  .arco-table-cell {
    .arco-table-cell-with-sorter {
      padding-right: 24px;
    }
  }
}
</style>
